package com.stu.widget;

import com.stu.aq.AQ;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class MotorScaleView extends View {
	private Paint textPaint, linePaint;
	private int tickDy, tickCount, majorX1, majorX2,
	  minorX1, minorX2, textY1, lineY1, height;
	private final static int textSize=12, majorSize=15, minorSize=10, minWidth=50;

	public MotorScaleView(Context context) {
		super(context);
		init();
	}

	public MotorScaleView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public MotorScaleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		lineY1 = 10;
		textY1 = 15;
		
		tickCount = ((AQ.motorMax - AQ.motorMin) / 50) + 1;
		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
		textPaint.setTextAlign(Align.LEFT);
		textPaint.setTextSize( textSize );

		Rect r = new Rect();
		String s = "1000";
		textPaint.getTextBounds( s, 0, s.length(), r );
		majorX1 = minWidth - majorSize;
		majorX2 = minWidth;
		minorX1 = minWidth - minorSize;
		minorX2 = minWidth;
		int majorTickCount = ((AQ.motorMax - AQ.motorMin)/200) + 1;
		height = (r.height() * majorTickCount) +
		  ((tickCount - majorTickCount) * (r.height() / 2));

		linePaint = new Paint();
		linePaint.setColor(Color.BLACK);
		linePaint.setStrokeWidth(1);
		linePaint.setStyle(Paint.Style.STROKE);
	}
/*
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
		setMeasuredDimension(minWidth, height);
	}
*/
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		height = h;
		tickDy = height / tickCount;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		int lineY = lineY1;
		int textY = textY1;
		for( int i = AQ.motorMax; i >= AQ.motorMin; i -= 50 ) {
			if( (i % 200) == 0 ) {
				canvas.drawText( String.valueOf(i), 0, textY, textPaint );
				linePaint.setStrokeWidth( 3 );
				canvas.drawLine( majorX1, lineY, majorX2, lineY, linePaint );
			} else {
				linePaint.setStrokeWidth( 1 );
				canvas.drawLine( minorX1, lineY, minorX2, lineY, linePaint );
			}
			lineY += tickDy;
			textY += tickDy;
		}
	}

}
